package com.cxy.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.cxy.pojo.Result;
import com.cxy.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //获取请求
        String url = request.getRequestURI();
        log.info("获取请求url:{}",url);
        //判断请求是否是login
        if(url.contains("login")){
            log.info("请求为登录请求，放行");
            return true;
        }
        //获取请求头，判断请求头中是否有token
        String jwt = request.getHeader("token");
        if(!StringUtils.hasLength(jwt)){
            //利用fastJson来将错误结果返回,利用响应对象的getWriter将结果响应给浏览器
            Result notLogin = Result.error("NOT_LOGIN");
            String s = JSONObject.toJSONString(notLogin);
            response.getWriter().write(s);
            return false;
        }
        //解析JWT
        try {
            jwtUtils.parseJWT(jwt);
        }catch (Exception e){
            e.printStackTrace();
            log.info("解析令牌出现错误，返回未登录错误信息");
            Result notLogin = Result.error("NOT_LOGIN");
            String s = JSONObject.toJSONString(notLogin);
            response.getWriter().write(s);
            return false;
        }
        //放行
        log.info("校验成功");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
